//
//  SurDataShareObj.m
//  wAudioShare
//
//  Created by 赵帅 on 14-1-14.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "SurDataShareObj.h"
#import "AsyncUdpSocket.h"
#import "SurGroupObject.h"

@interface SurDataShareObj()
{
    AsyncUdpSocket * listenSocket;
    NSLock * theLock;
    NSTimer * checkTimer;
}

@end

@implementation SurDataShareObj

static SurDataShareObj *sharedObj = nil;

+(SurDataShareObj*)sharedInstance{
    if (sharedObj == nil) {
        sharedObj = [[super allocWithZone:NULL]init];
        sharedObj.groupArray = [NSMutableArray array];
        sharedObj.allDeviceArray = [NSMutableArray array];
    }
    return sharedObj;
}

-(id)init
{
    if(self = [super init])
    {
        theLock = [[NSLock alloc] init];
    }
    return self;
}

-(void)listen
{
    dispatch_async(dispatch_get_main_queue(), ^{
        listenSocket=[[AsyncUdpSocket alloc] initWithDelegate:self];
        
        NSError *error = nil;
        [listenSocket bindToPort:7042 error:&error];
        
        if (error) {
            NSLog(@"error: %@",error);
        }
        
        [listenSocket receiveWithTimeout:-1 tag:1];
    });
    
    checkTimer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(checkTimerMethod) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:checkTimer forMode:NSDefaultRunLoopMode];
}

#pragma mark - ssdp callback methods
- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock
     didReceiveData:(NSData *)data
            withTag:(long)tag
           fromHost:(NSString *)host
               port:(UInt16)port{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self newMessageComing:data socket:sock];
    });
    
    return YES;
}

-(void)newMessageComing:(NSData *)data socket:(AsyncUdpSocket *)sock
{
    //必须放主线程 orz
    dispatch_async(dispatch_get_main_queue(), ^{
        [sock receiveWithTimeout:-1 tag:1];
    });
    
    NSMutableString * string = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    if(![string hasPrefix:@"Notify="] || [string rangeOfString:@"ip"].location == NSNotFound) return;
    [string replaceOccurrencesOfString:@"Notify=" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [string length])];
    
    NSArray * parseArray = [string componentsSeparatedByString:@","];
    
    NSMutableDictionary * deviceDic = [self makeRecordDictionary:parseArray];
    
    if(deviceDic[@"name"] == 0)
    {
        return;
    }
    
    [deviceDic setObject:[NSDate date] forKey:@"time"];
    
    [self dealWithComingDevice:deviceDic];
}

- (void)onUdpSocket:(AsyncUdpSocket *)sock didNotReceiveDataWithTag:(long)tag dueToError:(NSError *)erro
{
    NSLog(@"error tag: %ld",tag);
}

-(NSMutableDictionary *)makeRecordDictionary:(NSArray *)parseArray
{
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    for(NSString * str1 in parseArray)
    {
        NSArray * arr = [str1 componentsSeparatedByString:@":"];
        [dic setObject:arr[1] forKey:arr[0]];
    }
    return dic;
}

-(void)dealWithComingDevice:(NSDictionary *)deviceDic
{
    [theLock lock];
    //更新时间戳
    NSMutableDictionary * deivce = [self isExistInRecord:deviceDic[@"name"]];
    if(deivce == nil)
    {
        [[SurDataShareObj sharedInstance].allDeviceArray addObject:deviceDic];
    }
    else
    {
        [deivce setObject:[NSDate date] forKey:@"time"];
    }
    
    SurGroupObject * groupObj = [self isInOneGroup:deviceDic[@"name"]];
    if(groupObj != nil)
    {
        if([deviceDic[@"group"] length] == 0)//无groupname从组中删除
        {
            [groupObj.audioGroup removeObject:deviceDic[@"name"]];
            if([groupObj.audioGroup count] == 0)
            {
                [[SurDataShareObj sharedInstance].groupArray removeObject:groupObj];
            }
        }
        else if(![deviceDic[@"group"] isEqualToString:groupObj.groupName])//获得的组名和当前所在的组不一样
        {
            //从旧组删除
            [groupObj.audioGroup removeObject:deviceDic[@"name"]];
            if([groupObj.audioGroup count] == 0)
            {
                [[SurDataShareObj sharedInstance].groupArray removeObject:groupObj];
            }
            
            [self addDevice:deviceDic[@"name"] inGroup:deviceDic[@"group"]];
        }
    }
    else if([deviceDic[@"group"] length] != 0)
    {
        [self addDevice:deviceDic[@"name"] inGroup:deviceDic[@"group"]];
    }
    [theLock unlock];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if([_delegate respondsToSelector:@selector(newSurDataReceived)])
        {
            [_delegate newSurDataReceived];
        }
    });
}

-(NSMutableDictionary *)isExistInRecord:(NSString *)name
{
    for(NSMutableDictionary * dic in [SurDataShareObj sharedInstance].allDeviceArray)
    {
        if([name isEqualToString:dic[@"name"]])
            return dic;
    }
    return nil;
}

-(SurGroupObject *)isInOneGroup:(NSString *)name
{
    for(SurGroupObject * obj in [SurDataShareObj sharedInstance].groupArray)
    {
        for(NSString * deviceName in obj.audioGroup)
        {
            if([deviceName isEqualToString:name])
            {
                return obj;
            }
        }
    }
    
    return nil;
}

-(void)addDevice:(NSString *)name inGroup:(NSString *)groupName
{
    BOOL isExsit = NO;
    //添加到新组
    for(SurGroupObject * obj in [SurDataShareObj sharedInstance].groupArray)
    {
        if([obj.groupName isEqualToString:groupName])
        {
            isExsit = YES;
            [obj.audioGroup addObject:name];
            break;
        }
    }
    
    //建新组
    if(isExsit == NO)
    {
        SurGroupObject * obj = [[SurGroupObject alloc] init];
        obj.groupName = groupName;
        [obj.audioGroup addObject:name];
        
        [[SurDataShareObj sharedInstance].groupArray addObject:obj];
    }
}

-(void)checkTimerMethod
{
    [theLock lock];
    NSMutableArray * deleteArray = [NSMutableArray array];
    
    for(NSDictionary * dic in self.allDeviceArray)
    {
        NSDate * date = dic[@"time"];
        int interval = (int)[date timeIntervalSinceNow];
        
        if(abs(interval) >= 20)
        {
            SurGroupObject * groupObj = [self isInOneGroup:dic[@"name"]];
            [groupObj.audioGroup removeObject:dic[@"name"]];
            if([groupObj.audioGroup count] == 0)
            {
                [[SurDataShareObj sharedInstance].groupArray removeObject:groupObj];
            }
            
            [deleteArray addObject:dic];
        }
    }
    
    for(NSDictionary * dic in deleteArray)
    {
        [self.allDeviceArray removeObject:dic];
    }

    [theLock unlock];
        
    dispatch_async(dispatch_get_main_queue(), ^{
        if([_delegate respondsToSelector:@selector(newSurDataReceived)])
        {
            [_delegate newSurDataReceived];
        }
    });
}

@end
